package com.ztom.hard;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * 数据流的中位数
 * <p>
 * https://leetcode-cn.com/problems/shu-ju-liu-zhong-de-zhong-wei-shu-lcof/
 *
 * @author ZhangTao
 */
public class Code03MedianFinder {

    class MedianFinder {

        private PriorityQueue<Integer> big;
        private PriorityQueue<Integer> small;

        /** initialize your data structure here. */
        public MedianFinder() {
            this.big = new PriorityQueue<>(Comparator.reverseOrder());
            this.small = new PriorityQueue<>();
        }

        public void addNum(int num) {
            if (small.isEmpty()) {
                small.offer(num);
                return;
            }
            if (big.size() != small.size()) {
                small.offer(num);
                big.offer(small.poll());
            } else {
                big.offer(num);
                small.offer(big.poll());
            }
        }

        public double findMedian() {
            return big.size() != small.size()
                    ? small.peek()
                    : (big.peek() + small.peek()) / 2.0;
        }
    }
}
